package com.jintian.smart.kernel.flowable.flowable.agenda;

import com.jintian.smart.kernel.core.flow.ProcessControl;
import com.jintian.smart.kernel.flowable.component.ProcessContextProvider;
import com.jintian.smart.kernel.flowable.context.DefaultProcessContext;
import org.flowable.bpmn.model.FlowNode;
import org.flowable.bpmn.model.InclusiveGateway;
import org.flowable.bpmn.model.SequenceFlow;
import org.flowable.bpmn.model.UserTask;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.impl.agenda.TakeOutgoingSequenceFlowsOperation;
import org.flowable.engine.impl.context.BpmnOverrideContext;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.flowable.engine.impl.util.CommandContextUtil;

import com.fasterxml.jackson.databind.node.ObjectNode;

public class CustomTakeOutgoingSequenceFlowsOperation extends TakeOutgoingSequenceFlowsOperation {
    public CustomTakeOutgoingSequenceFlowsOperation(CommandContext commandContext, ExecutionEntity executionEntity, boolean evaluateConditions) {
        super(commandContext, executionEntity, evaluateConditions);
    }

    @Override
    protected void leaveFlowNode(FlowNode flowNode) {
        if ((flowNode instanceof InclusiveGateway || flowNode instanceof UserTask) && flowNode.getOutgoingFlows().size() > 1) {
            DefaultProcessContext processContext = ProcessContextProvider.getCurrentProcessContext();
            ProcessControl control = processContext.getProcessControl();
            if (control.getFlowTos().size() > 0) {
                for (SequenceFlow squenceFlow : flowNode.getOutgoingFlows()) {
                    if (squenceFlow.getTargetFlowElement() instanceof UserTask) {
                        String activity = ((UserTask) squenceFlow.getTargetFlowElement()).getId();
                        if (control.getFlowTo(activity) == null) {
                            ObjectNode definitionInfoNode = BpmnOverrideContext.getProcessDefinitionInfoNode(this.execution.getProcessDefinitionId());
                            CommandContextUtil.getProcessEngineConfiguration().getDynamicBpmnService().changeSequenceFlowCondition(squenceFlow.getId(), "${false}", definitionInfoNode);
                        }
                    }
                }
            }
        }
        super.leaveFlowNode(flowNode);
    }
}
